package com.caiden_micheal.dynamic.workflow.service.impl;

import com.caiden_micheal.base.constant.LoggerHead;
import com.caiden_micheal.base.domain.AjxResult;
import com.caiden_micheal.base.dto.PageDTO;
import com.caiden_micheal.base.utils.BaseContext;
import com.caiden_micheal.base.utils.JsonValidator;
import com.caiden_micheal.base.vo.PageVo;
import com.caiden_micheal.dynamic.form_workflow.domain.FormWorkflow;
import com.caiden_micheal.dynamic.form_workflow.mapper.FormWorkflowMapper;
import com.caiden_micheal.dynamic.workflow.domain.DynamicWorkflow;
import com.caiden_micheal.dynamic.workflow.dto.*;
import com.caiden_micheal.dynamic.workflow.mapper.DWorkflowMapper;
import com.caiden_micheal.dynamic.workflow.service.DWorkflowService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.List;
import java.util.Objects;

@Service
public class DWorkflowServiceImpl implements DWorkflowService {
    private static final Logger logger = LoggerFactory.getLogger(DWorkflowServiceImpl.class);

    @Autowired
    private DWorkflowMapper dWorkflowMapper;
    @Autowired
    private FormWorkflowMapper formWorkflowMapper;

    @Override
    public AjxResult addDWorkflow(AddDWorkflowDTO addDWorkflowDTO) {
        if (addDWorkflowDTO == null || addDWorkflowDTO.getNodes() == null ||
                addDWorkflowDTO.getEdges() == null) {
            logger.warn("参数传入有误, dynamicWorkflowDTO: " + addDWorkflowDTO);
            return AjxResult.paramError("参数传递有误");
        }
        if (!(JsonValidator.validJSON(addDWorkflowDTO.getEdges()) && JsonValidator.validJSON(addDWorkflowDTO.getNodes()))) {
            return AjxResult.paramError("参数传递有误，非JSON字符串");
        }
        try {
            if (addDWorkflowDTO.getId() == null) {
                if (addDWorkflowDTO.getDisplayName() == null) {
                    return AjxResult.paramError("参数传递有误");
                } else {
                    DynamicWorkflow dynamicWorkflow = dWorkflowMapper.findByDisplayName(addDWorkflowDTO.getDisplayName());
                    if (dynamicWorkflow != null) {
                        return AjxResult.paramError("审批流名称已存在");
                    }
                    dynamicWorkflow = new DynamicWorkflow();
                    BeanUtils.copyProperties(addDWorkflowDTO, dynamicWorkflow);
                    dynamicWorkflow.setCreatorId(Long.valueOf(BaseContext.getInfo().get("userId").toString()));
                    dynamicWorkflow.setCreatorUsername(String.valueOf(BaseContext.getInfo().get("username")));
                    dWorkflowMapper.insertWorkflow(dynamicWorkflow);
                    return AjxResult.success(dynamicWorkflow.getId());
                }
            } else {
                DynamicWorkflow dynamicWorkflow = dWorkflowMapper.findById(addDWorkflowDTO.getId());
                if (dynamicWorkflow == null) {
                    return AjxResult.paramError("审批流不存在");
                } else {
                    List<FormWorkflow> formWorkflowByWorkflowId = formWorkflowMapper.findFormWorkflowByWorkflowId(addDWorkflowDTO.getId());
                    if (formWorkflowByWorkflowId != null && formWorkflowByWorkflowId.size() != 0) {
                        return AjxResult.paramError("该审批流模板已被" + formWorkflowByWorkflowId.size() + "个逻辑流程模板引用，无法直接操作");
                    }
                }
                if (dynamicWorkflow.getDisplayName() != null) {
                    if (!Objects.equals(addDWorkflowDTO.getDisplayName(), dynamicWorkflow.getDisplayName())) {
                        DynamicWorkflow tempDWorkflow = dWorkflowMapper.findByDisplayName(addDWorkflowDTO.getDisplayName());
                        if (tempDWorkflow != null) {
                            return AjxResult.paramError("审批流模板名称已存在");
                        } else {
                            dynamicWorkflow.setDisplayName(addDWorkflowDTO.getDisplayName());
                        }
                    }
                }
                dynamicWorkflow.setEdges(addDWorkflowDTO.getEdges());
                dynamicWorkflow.setNodes(addDWorkflowDTO.getNodes());
                dWorkflowMapper.updateWorkflow(dynamicWorkflow);
                return AjxResult.success(dynamicWorkflow.getId());
            }
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Override
    public PageDTO findDWorkflowByCondition(FindDWorkflowPageQueryDTO findDWorkflowPageQueryDTO) {
        PageVo page = findDWorkflowPageQueryDTO.getPage();
        if (page == null) {
            logger.warn(LoggerHead.warnHead() + "findDWorkflowPageQueryDTO.page is Null!");
            return null;
        }
        page.setCurrentIndex((long) (page.getCurrentPage() - 1) * page.getPageSize());
        List<DynamicWorkflow> dWorkflowList = dWorkflowMapper.findDWorkflowByCondition(findDWorkflowPageQueryDTO);
        page.setCount(dWorkflowMapper.findDWorkflowByConditionCount(findDWorkflowPageQueryDTO));
        return new PageDTO(dWorkflowList, page);
    }

    @Override
    public AjxResult findDWorkflowOne(FindDWorkflowOneDTO findDWorkflowOneDTO) {
        if (findDWorkflowOneDTO == null || findDWorkflowOneDTO.getId() == null) {
            return AjxResult.paramError("参数传递有误");
        }
        DynamicWorkflow dynamicWorkflow = dWorkflowMapper.findById(findDWorkflowOneDTO.getId());
        if (dynamicWorkflow == null) {
            return AjxResult.paramError("审批流不存在");
        }
        if (findDWorkflowOneDTO.getPermissionFlag() == null || findDWorkflowOneDTO.getPermissionFlag()) {
            if (!Objects.equals(dynamicWorkflow.getCreatorId(), Long.valueOf(BaseContext.getInfo().get("userId").toString()))) {
                return AjxResult.paramError("审批流不存在");
            }
        }
        return AjxResult.success(dynamicWorkflow);
    }

    @Transactional
    @Override
    public AjxResult findWorkflowSelectData(FindWorkflowSelectDataDTO findWorkflowSelectDataDTO) {
        if (findWorkflowSelectDataDTO == null || findWorkflowSelectDataDTO.getDisplayName() == null) {
            return AjxResult.paramError("参数传递有误");
        }
        try {
            return AjxResult.success(dWorkflowMapper.findWorkflowSelectData(findWorkflowSelectDataDTO.getDisplayName()));
        } catch (Exception e) {
            logger.error(e.toString());
            return AjxResult.unknownError("数据库操作异常");
        }
    }

    @Transactional
    @Override
    public AjxResult removeDWorkflow(RemoveDWorkflow removeDWorkflow) {
        if (removeDWorkflow == null || removeDWorkflow.getId() == null) {
            return AjxResult.paramError("参数传递有误");
        }
        try {
            List<FormWorkflow> formWorkflowByWorkflowId = formWorkflowMapper.findFormWorkflowByWorkflowId(removeDWorkflow.getId());
            if (formWorkflowByWorkflowId != null && formWorkflowByWorkflowId.size() != 0) {
                return AjxResult.paramError("该审批流模板已被" + formWorkflowByWorkflowId.size() + "个逻辑流程模板引用，无法直接操作");
            }
            dWorkflowMapper.removeDWorkflow(removeDWorkflow.getId());
            return AjxResult.success("删除成功");
        } catch (Exception e) {
            logger.error(e.toString());
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return AjxResult.unknownError("数据库操作异常");
        }
    }
}
